package com.ruoyi.base.controller;

import com.ruoyi.base.enums.ExceptionEnum;
import com.ruoyi.base.exception.SysException;
import com.ruoyi.base.page.PageData;
import com.ruoyi.base.pojo.HttpResult;

import java.util.List;
import java.util.function.Function;

/**
 * web层通用数据处理
 *
 * @author ruoyi
 */
public class BaseController {
    /**
     * 返回结果
     */
    protected <T> HttpResult<T> data(T data) {
        return new HttpResult<>(data);
    }

    protected <T> HttpResult<T> data(T data, String msg) {
        return new HttpResult<>(data, msg);
    }

    /**
     * 操作成功自定义描述
     */
    protected HttpResult<String> msg(String msg) {
        return HttpResult.success(msg);
    }

    /**
     * 操作成功
     */
    protected HttpResult<String> success() {
        return HttpResult.success();
    }

    /**
     * 操作失败
     */
    protected HttpResult<String> error() {
        return HttpResult.error();
    }

    /**
     * 操作失败自定义描述
     */
    protected HttpResult<String> error(String msg) {
        return HttpResult.error(msg);
    }

    /**
     * 返回分页结果
     */
    protected <T> HttpResult<PageData<T, T>> page(List<T> list) {
        return data(new PageData<>(list, x -> x));
    }

    /**
     * 返回分页结果
     */
    protected <DO, DTO> HttpResult<PageData<DO, DTO>> page(List<DO> list, Function<DO, DTO> consumer) {
        return data(new PageData<>(list, consumer));
    }

    /**
     * 抛出异常
     */
    protected SysException exception(ExceptionEnum e) {
        return new SysException(e);
    }

    /**
     * 抛出异常
     */
    protected SysException exception(String msg) {
        return new SysException(msg);
    }

    /**
     * 抛出异常
     */
    protected SysException exception(Exception e) {
        return new SysException(e);
    }

    /**
     * 抛出异常
     */
    protected RuntimeException exception(String msg, Exception e) {
        return new RuntimeException(msg, e);
    }
}
